<template>
  <Layout>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!"
           border :columns="columns1" :data="dataTable" :loading="loadingItems">
    </Table>

    <Modal title="环保监督检查问题" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow"
           :width=700 :styles="{height:'500px'}" class-name='limit-height-dialog' >
      <Row>
        <Col span="24">
          <Form ref="dialogForm1" :class="mode === 'view'?'modal-view-detail':'rpt-form'" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?100:null"
                :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='问题类别：' prop='problemCategory'>
                  <div v-if="mode === 'view'">{{ dataToView.problemCategoryName }}</div>
                  <Select v-else v-model="dataToView.problemCategory" label-in-value @on-change="selectChange">
                    <Option v-for="item in environmentProtectionList" :value="item.codingCodeId"
                            :key="item.codingCodeId">{{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='检查时间：' prop='checkTime'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.checkTime) }}</div>
                  <DatePicker v-else type="date" placeholder="请选择日期" style="width: 100%"
                              v-model='dataToView.checkTime'
                              :editable="editable"></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="11">
                <FormItem label='完成时限：' prop='completeTime'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.completeTime) }}</div>
                  <DatePicker v-else type="date" placeholder="请选择日期" style="width: 100%"
                              v-model='dataToView.completeTime' :options="options"
                              :disabled="dataToView.exist"
                              :editable="editable"></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='整改状态：' prop='state'>
                  <div v-if="mode === 'view'">{{renderState(dataToView.state)}}</div>
                  <Select v-else v-model="dataToView.state" @on-change="onState"
                          :disabled="dataToView.procinstState == '1' || dataToView.procinstState == '2'">
                    <Option value="NOT_RECTIFIED">待整改</Option>
                    <Option value="START">整改中</Option>
                    <Option value="OPEN">已完成</Option>
                    <Option value="DELAY" disabled>延期</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='问题描述：' prop='problemDesc'>
                  <div v-if="mode === 'view'">{{ dataToView.problemDesc }}</div>
                  <Input v-else class='' show-word-limit :maxlength="1024" type='textarea'
                         v-model='dataToView.problemDesc'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='整改方案：'>
                  <div v-if="mode === 'view'">{{ dataToView.rectifyPlan }}</div>
                  <Input v-else class='' @input="inputRectifyPlan" show-word-limit :maxlength="1024" type='textarea'
                         v-model='dataToView.rectifyPlan'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='当前进展描述：' prop='completion'>
                  <div v-if="mode === 'view'">{{ dataToView.completion }}</div>
                  <Input v-else class='' show-word-limit :maxlength="1024" type='textarea'
                         v-model='dataToView.completion'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem v-if="mode === 'view'" label="整改附件：">
                  <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles">
                    <a @click="downloadFiles(item,index)"><span style="color: #3399ff;margin-left: 5px">{{
                        item.fileName
                      }}</span></a>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
                <FormItem v-else label="整改附件：">
                  <div>
                    <Upload ref="upload"
                            :before-upload="(file) => { beforeUpload1(file, 'id','EnQuestionDetailForApproval') }"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles" :key='index'>
                    <a @click="downloadFiles(item,index)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash"
                            @click="removeFile1(item.id, 'id','EnQuestionDetailForApproval')"
                            style="margin-left: 5px;margin-bottom: 3px"/>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm1')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>

    <Modal title="环保监督检查问题详情" :transfer=false v-model="modal3" class="modal-view-detail" :width=700
           :styles="{top: '10px'}">
      <Form ref="viewForm" :label-width="100">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="问题类别：">
              <div>
                {{ dataToView.problemCategoryName }}
              </div>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="检查时间：">
              {{ renderViewDate(dataToView.checkTime) }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="完成时限：">
              {{ renderViewDate(dataToView.completeTime) }}
            </FormItem>
          </Col>
          <Col span="11">

          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="问题描述：">
              {{ dataToView.problemDesc }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='整改方案：' prop='rectifyPlan'>
              {{ dataToView.rectifyPlan }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='当前进展描述：' prop='completion'>
              {{ dataToView.completion }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="整改附件：">
              <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles">
                <a @click="downloadFiles(item,index)"><span style="color: #3399ff;margin-left: 5px">{{
                    item.fileName
                  }}</span></a>
                <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="modal3=false">关闭</Button>
      </div>
    </Modal>
    <Modal title="问题延期" :transfer=false v-model="modal4"  :width=700 class-name='limit-height-dialog'
           :styles="{height:'400px',top: '100px'}">
      <Form ref="extensionForm" :model="dataToExtension"  :rules="extensionShow" class="rpt-form"
            :show-message="false" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg" >
          <Col span="11">
            <FormItem label="延期时间：" prop="completeTime">
              <DatePicker type="date" placeholder="请选择日期" style="width: 100%"
                          v-model='dataToExtension.completeTime' :options="options"
                          :editable="editable"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="审批人：" prop="userId">
              <Select v-model="dataToExtension.userId" label-in-value @on-change="getSelectModelData">
                <Option v-for="item in approvers" :value="item.userId"
                        :key="item.userId">{{ item.userName }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='延期说明：' prop='explain'>
              <Input class='' type='textarea' v-model='dataToExtension.explain'></Input>
            </FormItem>
          </Col>
        </Row>

      </Form>
      <div slot="footer">
        <Button  type="primary" class='ivu-btn-save' :loading="loadingExtension" @click="submitExtension('extensionForm')">确定</Button>
        <Button  type="primary" class='ivu-btn-cancel' @click="cancel">取消</Button>
      </div>
    </Modal>

    <Modal :transfer=false footer-hide v-model="modal5" :width=900>
      <userManager :model="true" :companyId="-1" @getSelectModelData="getSelectModelData">
      </userManager>
    </Modal>
  </Layout>
</template>

<script>
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {Api} from "@/api";
import userManager from '../../../base/authorityManager/userManager'
import _deepclone from 'lodash/cloneDeep'

export default {
  name: "EnProQuestionDetail",
  components: {userManager},
  props: {
    dataTable: {
      type: Array,
      default: [],
    },
    loadingItems: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ...this.createCommonDataField(),

      environmentProtectionList: [],
      modal3: false,
      modal4: false,
      modal5: false,
      editable: false,
      loadingExtension: false,
      dataToExtension: {},
      options: {
        disabledDate(date) {
          return date && date.valueOf() <= Date.now();
        },
      },
      columns1: [

        {
          title: '序号', width: 80, fixed: 'left', align: 'center', render: (h, params) => {
            return h('span', params.index + 1);
          }
        },
        {key: 'problemDesc', title: '问题描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'problemCategoryName', title: '问题类别', align: 'center', minWidth: 150},
        {key: 'rectifyPlan', title: '整改方案描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'completion', title: '当前进展描述', align: 'center', minWidth: 200, tooltip: true},
        {key: 'checkTime', title: '检查时间', align: 'center', minWidth: 150, render: this.renderCellDate},
        {
          key: 'completeTime',
          title: '完成时限',
          align: 'center',
          minWidth: 150,
          render: this.renderCellDate
        },
        {
          key: 'finishTime',
          title: '完成时间',
          align: 'center',
          minWidth: 150,
          render: this.renderCellDate
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 230,
          align: 'center',
          render: (h, params) => {
            if (params.row.state == 'OPEN') {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '问题延期'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.viewData(params);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            } else {
              if (!params.row.exist){
                //新增
                return h('div', [
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce'}
                  }, '问题延期'),
                  h('Divider', {props: {type: 'vertical'}}, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px',},
                    on: {
                      click: () => {
                        this.viewData(params);
                      }
                    }
                  }, '详情'),
                  h('Divider', {props: {type: 'vertical'}}, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    disabled: true,
                    style: {fontSize: '14px'},
                    on: {
                      click: () => {
                        this.edit(params);

                      }
                    }
                  }, '修改'),
                  h('Divider', {props: {type: 'vertical'}}, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: 'red'},
                    on: {
                      click: () => {
                        this.$Modal.confirm({
                          title: '提示',
                          content: '<p>确认删除此行数据？</p>',
                          onOk: () => {
                            this.$emit("delete", params.index)
                          },
                          onCancel: () => {
                          }
                        });
                      }
                    }
                  }, '删除')
                ]);
              }else{
                //修改 判断是否存在其它延期申请
                if(params.row.procinstState == '1' || params.row.procinstState == '2'){
                  return h('div', [
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      style: {fontSize: '14px', color: '#c5c8ce'}
                    }, '问题延期'),
                    h('Divider', {props: {type: 'vertical'}}, ''),
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      style: {fontSize: '14px',},
                      on: {
                        click: () => {
                          this.viewData(params);
                        }
                      }
                    }, '详情'),
                    h('Divider', {props: {type: 'vertical'}}, ''),
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      disabled: true,
                      style: {fontSize: '14px'},
                      on: {
                        click: () => {
                          this.edit(params);

                        }
                      }
                    }, '修改'),
                    h('Divider', {props: {type: 'vertical'}}, ''),
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      style: {fontSize: '14px', color: '#c5c8ce'}
                    }, '删除'),
                  ]);
                }else{
                  return h('div', [
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      style: {fontSize: '14px',},
                      on: {
                        click: () => {
                          let dataToExtension = _deepclone(params.row);
                          this.dataToExtension = {
                            completeTime:dataToExtension.completeTime,
                            questionId:dataToExtension.id,
                          };
                          this.modal4 = true;
                        }
                      }
                    }, '问题延期'),
                    h('Divider', {props: {type: 'vertical'}}, ''),
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      style: {fontSize: '14px',},
                      on: {
                        click: () => {
                          this.viewData(params);
                        }
                      }
                    }, '详情'),
                    h('Divider', {props: {type: 'vertical'}}, ''),
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      disabled: true,
                      style: {fontSize: '14px'},
                      on: {
                        click: () => {
                          this.edit(params);

                        }
                      }
                    }, '修改'),
                    h('Divider', {props: {type: 'vertical'}}, ''),
                    h('A', {
                      props: {type: 'primary', size: 'small'},
                      style: {fontSize: '14px', color: 'red'},
                      on: {
                        click: () => {
                          this.$Modal.confirm({
                            title: '提示',
                            content: '<p>确认删除此行数据？</p>',
                            onOk: () => {
                              this.$emit("delete", params.index)
                            },
                            onCancel: () => {
                            }
                          });
                        }
                      }
                    }, '删除')
                  ]);
                }

              }

            }
          }
        }

      ],
      extensionShow:{
        userId: [{required: true, message: '请选择审批人', trigger: 'change'}],
        explain: [{required: true, message: '请填写延期申请', trigger: 'change'}],
        // completeTime: [{required: true, message: '请选择完成时限', trigger: 'change', type: 'date'}],
        completeTime: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      ruleCustom: {
        problemCategory: [{required: true, message: '请选择问题类别', trigger: 'change'}],
        checkTime: [{required: true, message: '请选择检查时间', trigger: 'change', type: 'date'}],
        completeTime: [{required: true, message: '请选择完成时限', trigger: 'change', type: 'date'}],
        problemDesc: [{required: true, message: '请填写问题描述', trigger: 'change'}],
        state: [{required: true, message: '请填写问题描述', trigger: 'change'}],
        rectifyPlan: [{required: true, message: '请填写整改方案', trigger: 'change'}],
      },
      addMod: false,
      approvers: [],
    }

  },
  async mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 450;
    this.$http.get(Api.queryCodeDetailBySortId + '/NOT-00006', {params: {}}).then((res) => {
      this.environmentProtectionList = res.data.data;
    });
    this.$http.get(Api.getEnProQuestionAccountApprovers + "/b93eb368d0994a768c0eb84ed5fa794c").then((res) => {
      this.approvers = res.data.data;
    });
  },
  methods: {
    ...pageCommonFunction,
    renderState(state){
      switch (state){
        case "START":
          return '整改中';
        case "NOT_RECTIFIED":
          return '待整改';
        case "OPEN":
          return '已完成';
        case "DELAY": return '延期';
      }

    },
    onState(data) {
      switch (data) {
        case "NOT_RECTIFIED":
          this.dataToView.state = 'NOT_RECTIFIED';
          this.dataToView.finishTime = null;
          break;
        case "START":
          this.dataToView.state = 'START';
          this.dataToView.finishTime = null;
          break;
        case "OPEN":
          this.dataToView.state = 'OPEN';
          this.dataToView.finishTime = new Date();
          break;
      }
    },
    inputRectifyPlan(value) {
      if (value && this.dataToView.state == 'NOT_RECTIFIED') {
        this.dataToView.state = 'START'
      } else if ((!value) && this.dataToView.state == 'START') {
        this.dataToView.state = 'NOT_RECTIFIED'
      }
    },
    submitExtension(name) {
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (valid) {
          _this.loadingExtension = true;
          let url = Api.extensionEnProQuestionAccount;
          this.$http.post(url, _this.dataToExtension).then((res) => {
            if (res.data.status == '200') {
              _this.$Message.success("上报成功")
              _this.$emit('query');
              _this.modal4 = false;
            }else{
              this.$Message.error(res.data.msg);
            }
            _this.loadingExtension = false;
          }).catch(e=>{
            console.log(e)
          })
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    cancel(){
      this.modal4 = false;
    },
    getSelectModelData(row) {
      this.dataToExtension.userId = row.value;
      this.dataToExtension.userName = row.label;
    },
    getUser(){
      this.modal5 = true;
    },
    add(checkTime) {
      this.addMod = true;
      this.dataToView = {
        id: this.get_uuid(),
        state: 'NOT_RECTIFIED'
      };
      this.mode = 'add'
      this.dataToView.checkTime = checkTime
      this.dialogShow = true;
    },
    async edit(params) {
      this.addMod = false;
      this.mode = 'edit'
      // this.editData(params);
      let dataToView = _deepclone(params.row);
      this.dataToView = dataToView;
      this.dataToView.index = params.index;
      this.dialogShow = true;
      await this.afterDataToViewInit();
    },
    async afterDataToViewInit() {
      await this.getFiles1('id', 'EnQuestionDetailForApproval');
    },

    selectChange(data) {
      this.dataToView.problemCategory = data.value
      this.dataToView.problemCategoryName = data.label
    },
    submit(name) {
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (_this.dataToView.state == 'OPEN') {
            this.$Modal.confirm({
              title: '提示',
              content: '<p>问题状态为“已完成”时不可继续修改删除，是否继续保存</p>',
              onOk: () => {
                _this.save();
              },
              onCancel: () => {
              }
            });
          } else {
            _this.save();
          }


        } else {
          this.$Message.error('请填报完整!');
        }
      })

    },

    save() {
      let _this = this;
      _this.dataToView.addMod = this.addMod;
      if (this.addMod) {
        _this.$emit("addSubmit", _deepclone(_this.dataToView))
        _this.dialogShow = false;
        _this.addMod = false;
      } else {
        _this.$emit("addSubmit", _deepclone(_this.dataToView))
        _this.dialogShow = false;
      }
    }

  }
}
</script>

<style scoped>
@import '../../../../index.css';
</style>
